package cn.wolfcode.luowowo.redis.redisService.impl;

import cn.wolfcode.luowowo.redis.key.RedisKeys;
import cn.wolfcode.luowowo.redis.redisService.IStrategyFavorRedisService;
import cn.wolfcode.luowowo.vo.FavorStrategyVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StrategyFavorRedisServiceImpl implements IStrategyFavorRedisService {


    @Autowired
    private StringRedisTemplate template;

    @Override
    public FavorStrategyVO getFavorRedis(String userInfoId) {
        //根据用户id拼接key
        String key = RedisKeys.USER_STRATEGY_FAVOR.join(userInfoId);
        //根据key获取在缓存中用户的攻略收藏数据(即FavorStrategyVO对象)
        FavorStrategyVO vo = null;
        if (template.hasKey(key)) {
            //如果key存在
            String listStr = template.opsForValue().get(key);
            //把list字符串转换成list
            // 注意:使用JSON.parseArray  参数二: 集合的泛型
            vo = JSON.parseObject(listStr, FavorStrategyVO.class);
        } else {
            vo = new FavorStrategyVO();
        }
        return vo;
    }

    @Override
    public void setFavorRedis(String userInfoId, List<String> list) {
        //根据用户id拼接key
        String key = RedisKeys.USER_STRATEGY_FAVOR.join(userInfoId);
        FavorStrategyVO vo = new FavorStrategyVO();
        //插入 收藏的攻略id集合
        vo.setFavorStrategyIds(list);
        //插入 当前用户id
        vo.setUserInfoId(userInfoId);
        template.opsForValue().set(key, JSON.toJSONString(vo));
    }

}
